<template>
  <div class="login w-image-fit w-flex-center">
    <div class="form-box">
      <p class="title">{{ config.projectName }}</p>
      <el-form ref="form" :model="form" :rules="rules" label-width="70px">
        <account-input v-model="form.name"/>
        <pass-input v-model="form.pass"/>
        <code-input v-model="form.code" ref="CodeInput"/>
        <div class="w-flex-center">
          <el-button style="width: 360px" type="primary" @click="onSubmit" :loading="loading">登录</el-button>
        </div>
        <p v-if="config.loginDescription" class="description">{{ config.loginDescription }}</p>
        <div class="w-text-right w-flex-between">
          <el-button type="text" @click="docsBtnClick">文档</el-button>
          <el-button type="text" @click="forgotPassword">忘记密码</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { Form } from 'element-ui'
import WPopView from '@/utils/popView'
import { ProjectConfigType } from '@/config/types'
import { PassInput, CodeInput, AccountInput, AccountRule, PassRule, CodeRule, CodeInputType } from '@/components/global/input'

@Component({
  name: 'ComLogin',
  components: {
    PassInput,
    CodeInput,
    AccountInput
  }
})
export default class Login extends Vue{
  /**
   * 配置信息
   */
  @Prop() config!: ProjectConfigType

  private loading = false

  form = {
    name: '',
    pass: '',
    code: ''
  }

  rules = {
    name: AccountRule,
    pass: PassRule,
    code: CodeRule
  }

  onSubmit() {
    (this.$refs.form as Form).validate((valid) => {
      if (valid) {
        const data = {
          ...this.form,
          uuid: (this.$refs.CodeInput as CodeInputType).uuid
        }
        this.loading = true
        this.$store.dispatch('LOGIN', data).then(() => {
          this.$emit('loginSuccess')
          WPopView.msgSuccess('登录成功')
        }).catch(() => {
          (this.$refs.CodeInput as CodeInputType).changeCode()
        }).finally(() => {
          this.loading = false
        })
      } else {
        return false;
      }
    });
  }

  docsBtnClick() {
    window.open('/wang-admin-api/public/docs/index.html')
  }

  forgotPassword() {
    this.$emit('forgotPassword')
  }
}
</script>

<style scoped lang="scss">
.login {
  width: 100%;
  height: 100vh;
  background-image: url("../../assets/img/login/login-bg.jpg");

  .form-box {
    padding: 30px;
    background-color: #fff;
    border-radius: 10px;
    width: 500px;

    .title {
      text-align: center;
      font-size: 30px;
      margin-top: 0;
    }

    .description {
      font-size: 12px;
      text-align: center;
      color: #ccc;
      line-height: 20px;
    }
  }
}
</style>
